﻿$(document).ready(function () {

    //If a link is clicked which contains '/media/' in the url call this code.
    $("a[href*='/media/']").click(function () {

        //Get the media path which is in the href.
        var mediaPath = $(this).attr("href");

        //Do an AJAX call to the server to get the media item based on the mediaPath.
        //If the media item has a property with the alias 'trackLabel' that value will be returned.
        $.ajax({
            type: "POST",
            async: false,
            url: "/umbraco/plugins/TrackMedia/TrackService.asmx/GetTrackLabel",
            data: '{ mediaPath: "' + mediaPath.replace(/^.*\/\/[^\/]+/, '') + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var trackLabel = msg.d;
                if (trackLabel == '') {
                    
                    //If no track label is found or the property is empty set a default label.
                    trackLabel = 'Media';
                }

                //Track the event with the track label.
                _gaq.push(['_trackEvent', 'Download', trackLabel, mediaPath]);
            }
        });
    });

});